package com.lbssoft.gpsbd.dao;

import com.lbssoft.gpsbd.model.CommandRecord;
import com.lbssoft.gpsbd.model.Log;
import com.lbssoft.gpsbd.model.LoginLog;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CommandRecordMapper {

	/**
	 * 写入命令记录
	 */
	@Insert("insert into lbs_command_record (sn,deviceId,cmdId,status,req) value (#{sn},#{deviceId},#{cmdId},#{status},#{req})")
	void add(CommandRecord record);

	/**
	 * 根据设备id获取最新流水号
	 * @param deviceId
	 * @return
	 */
	@Select("SELECT IF(COUNT(id)=0,0,max(sn))+1 as sn FROM lbs_command_record where deviceId = #{deviceId} ORDER BY sn desc limit 1")
	Integer getNewSn(@Param("deviceId") long deviceId);

	/**
	 * 将离线命令修改为未执行
	 * @param deviceId
	 */
	@Update("update `lbs_command_record` SET  `status` =4 WHERE deviceId = #{deviceId} and `status` =1")
	void updateUnexecuted(@Param("deviceId") long deviceId);

	/**
	 * 根据设备id和sn获取记录id
	 * @param deviceId
	 * @param sn
     * @return
     */
	@Select("SELECT id FROM lbs_command_record where deviceId = #{deviceId} AND sn = #{sn}")
	int getRecordId(@Param("deviceId") long deviceId,@Param("sn") int sn);

	/**
	 * 更新命令记录状态
	 * @param record
     */
	@Update("UPDATE lbs_command_record SET `status` = #{status},res = #{res},resTime = now() WHERE id = #{id}")
	void update(CommandRecord record);

	/**
	 * Track api
	 * 查询设备命令记录
	 * @param
	 */
	@Select("SELECT a.id, b.name, b.type, a.req, a.sn, a.`status`, a.reqTime, a.res, TIMESTAMPDIFF(SECOND, a.reqTime, a.resTime) AS time FROM lbs_command_record a LEFT JOIN lbs_commands b ON a.cmdId = b.id WHERE a.deviceId = #{deviceId} ORDER BY id DESC")
	List<CommandRecord> getList(@Param("deviceId") long deviceId);

}
